﻿using jinmaMesProxy.Model;
using Microsoft.Data.SqlClient;
using System.Reflection;
using System.Text;

namespace jinmaMesProxy.DataAccess
{
    public class ErpDbUpdater<TMain, TDetail> 
        where TMain : MainDetailModel<TDetail>
        where TDetail:DetailModel
    {
        private void InsertDb<T>(T data)
        {
            var ttype = typeof(T);
            var tableName = ttype.GetCustomAttribute<MyTableNameAttribute>().TableName;
            var sql_format = "INSERT INTO {0}({1}) VALUES({2}) ";
            var valueSeg = new StringBuilder();
            var colSeg = new StringBuilder();
            List<KeyValuePair<string, object>> ps = new List<KeyValuePair<string, object>>();
            foreach (var p in ttype.GetProperties())
            {
                var colAtt = p.GetCustomAttribute<MyColumnNameAttribute>();
                if (colAtt == null)
                    continue;
                colSeg.Append(colAtt.ColumnName + ",");
                string key = "@" + colAtt.ColumnName;
                valueSeg.Append(key + ",");
                ps.Add(new KeyValuePair<string, object>(key, p.GetValue(data)));
            }
            colSeg.Remove(colSeg.Length - 1, 1);
            valueSeg.Remove(valueSeg.Length - 1, 1);
            var sql = string.Format(sql_format, tableName, colSeg, valueSeg);
            var instance = ServiceLoader.GetService<ErpDbInstance>();
            using (var cmd = instance.MakeQueryCommand(sql, ps.ToArray()))
            {
                cmd.ExecuteNonQuery();
            }
        }
        public void Insert(TMain data)
        {
            InsertDb(data);
            foreach (var item in data.Details)
            {
                item.MainId = data.Id;
                InsertDb(item);
            }
        }
    }
}
